/*
 * @lc app=leetcode.cn id=54 lang=cpp
 *
 * [54] 螺旋矩阵
 *
 * https://leetcode.cn/problems/spiral-matrix/description/
 *
 * algorithms
 * Medium (48.93%)
 * Likes:    1136
 * Dislikes: 0
 * Total Accepted:    280.3K
 * Total Submissions: 572.8K
 * Testcase Example:  '[[1,2,3],[4,5,6],[7,8,9]]'
 *
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 *
 *
 *
 * 示例 1：
 *
 *
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 *
 *
 * 示例 2：
 *
 *
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 *
 *
 *
 *
 * 提示：
 *
 *
 * m == matrix.length
 * n == matrix[i].length
 * 1
 * -100
 *
 *
 */

// @lc code=start
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    vector<int> direction{0, 1, 0, -1, 0};
    vector<int> spiralOrder(vector<vector<int>> &matrix) {
        int m = matrix.size();
        if (m == 0) {
            return {};
        }
        int n = matrix[0].size();
        if (n == 0) {
            return {};
        }
        vector<int> ans;
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        int size = m * n;
        int flag = -1;
        int i = 0, j = 0;
        while (size) {
            if (flag == -1) {
                flag = 0;
                cout << "改变flag到0" << endl;
            }
            else if (flag == 3) {
                flag = 0;
                cout << "改变flag到0" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            else if (flag == 0) {
                flag = 1;
                cout << "改变flag到1" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            else if (flag == 1) {
                flag = 2;
                cout << "改变flag到2" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            else {
                flag = 3;
                cout << "改变flag到3" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            while (i >= 0 && i < m && j >= 0 && j < n && visited[i][j] == false) {
                visited[i][j] = true;
                cout << "i is " << i << ", "
                     << "j is " << j << "," << endl;
                cout << "输出" << matrix[i][j] << endl;
                ans.push_back(matrix[i][j]);
                --size;
                i += direction[flag];
                j += direction[flag + 1];
            }
            if (i == m) {
                i = m - 1;
            }
            else if (i == -1) {
                i = 0;
            }
            else if (j == n) {
                j = n - 1;
            }
            else if (j == -1) {
                j = 0;
            }
            else {
                i -= direction[flag];
                j -= direction[flag + 1];
            }
        }
        return ans;
    }
};
// @lc code=end
